package com.lanou.myim.adapter;

import android.content.Context;
import android.content.Intent;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.easemob.chat.EMGroup;
import com.lanou.myim.R;
import com.lanou.myim.custom.SlidingMenuView;
import com.lanou.myim.entity.MsgEty;
import com.lanou.myim.entity.MsgFromEty;
import com.lanou.myim.presenter.ConversationPresenterInterface;

import com.lanou.myim.tools.ParseSingleton;
import com.lanou.myim.tools.Utils;
import com.lanou.myim.ui.activity.PrivateChatActivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by dllo on 15/12/30.
 */
public class FragmentConversationAdapter extends BaseAdapter implements SlidingMenuView.SlidingMenuListener {
    private List<MsgEty> datas;
    private Context context;
    private ConversationPresenterInterface conversationPresenter;
    private SlidingMenuView mMenu = null;
    private List<EMGroup> groups;
    private Html.ImageGetter imageGetter;



    public FragmentConversationAdapter(final Context context, ConversationPresenterInterface conversationPresenter,List<EMGroup> groups) {
        this.conversationPresenter = conversationPresenter;
        datas = conversationPresenter.getMsgList();
        this.context = context;
        this.groups = groups;
        imageGetter = new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                int id = Integer.parseInt(source);
                Drawable d = context.getResources().getDrawable(id);
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                return d;
            }
        };
    }
//加载数据库
  public void refresh(List<MsgEty> datas){
      this.datas = datas;
      notifyDataSetChanged();
  }


    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public class ViewHolder {
        RelativeLayout relativeLayout;
        ImageView imageView;
        TextView name;
        TextView body;
        TextView time;
        Button menuStick;
        Button menuDelete;
        TextView unreadMsgTv;

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_conversation, parent, false);
            holder = new ViewHolder();
            holder.relativeLayout = (RelativeLayout) convertView.findViewById(R.id.conversation_item);
            holder.imageView = (ImageView) convertView.findViewById(R.id.friend_picture);
            holder.name = (TextView) convertView.findViewById(R.id.friend_name);
            holder.body = (TextView) convertView.findViewById(R.id.msg_last);
            holder.time = (TextView) convertView.findViewById(R.id.conversation_time);
            holder.menuStick = (Button) convertView.findViewById(R.id.btn_Stick);
            holder.menuDelete = (Button) convertView.findViewById(R.id.btn_delete);
            holder.unreadMsgTv = (TextView) convertView.findViewById(R.id.tv_unread_count);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        closeMenu();
        ((SlidingMenuView) convertView).setSlidingMenuListener(FragmentConversationAdapter.this);
        final Button stickBtn = holder.menuStick;
        stickBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (conversationPresenter.getStickName() == null) {
                    conversationPresenter.stickMsg(datas.get(position).getUserName());
                } else if (stickBtn.getText().equals("取消置顶")) {
                    conversationPresenter.unStickMsg();
                } else {
                    Toast.makeText(context, "已有消息置顶,请先取消置顶消息", Toast.LENGTH_SHORT).show();
                }
            }
        });
        holder.menuDelete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                conversationPresenter.deleteMsg(datas.get(position));
            }
        });
        if (datas.get(position).getUserName().equals(conversationPresenter.getStickName())){
            stickBtn.setText("取消置顶");
        }else {
            stickBtn.setText("置顶");
        }
        String name = datas.get(position).getUserName();
        for (EMGroup emGroup : groups){
            if (emGroup.getGroupId().equals(name)){
                name = emGroup.getGroupName();
            }
        }
        holder.name.setText(name);
        ParseSingleton.setDescr(datas.get(position).getUserName(), holder.name);
        final Date date = new Date(datas.get(position).getTime());
        SimpleDateFormat myFmt=new SimpleDateFormat("a hh:mm");
        holder.time.setText(myFmt.format(date));


        holder.body.setText(Html.fromHtml(datas.get(position).getBody(), imageGetter, null));

        int count = datas.get(position).getUnReadCount();
        if (count > 0){
            holder.unreadMsgTv.setVisibility(View.VISIBLE);
            holder.unreadMsgTv.setText(count+"");
        }else {
            holder.unreadMsgTv.setVisibility(View.GONE);
        }

       //解决listview复用带来的头像重复的问题
       holder.imageView.setImageResource(R.drawable.alert);
       ParseSingleton.setBitmap(datas.get(position).getUserName(), holder.imageView);


        holder.relativeLayout.getLayoutParams().width = Utils.getScreenWidth(context);
        holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (menuIsOpen())
                    closeMenu();
                EMGroup emGroup = null;
                String id = datas.get(position).getUserName();
                for (EMGroup group : groups){
                    if (id.equals(group.getGroupId())){
                        emGroup = group;
                    }
                }
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                if (emGroup != null){
                bundle.putSerializable("ID",new MsgFromEty("GROUP",null,emGroup.getGroupName(),emGroup.getGroupId()));
                }else {
                    bundle.putSerializable("ID",new MsgFromEty("FRIEND",id,null,null));
                }
                intent.setClass(context, PrivateChatActivity.class);
                intent.putExtras(bundle);
                context.startActivity(intent);

            }
        });


        return convertView;
    }

    public void onMenuIsOpen(SlidingMenuView slidingMenuView) {
        //当菜单处于打开状态,就对mMenu进行赋值
        mMenu = slidingMenuView;
    }


    public void onDownOrMove(SlidingMenuView slidingMenuView) {
        if (menuIsOpen()) {
            //如果菜单是打开的
            //现在正在打开或用户正在点击的菜单,不是原来打开的菜单,就将原来打开的菜单关闭
            if (mMenu != slidingMenuView) {
                closeMenu();

            }
        }

    }

    //判断菜单是否打开
    public boolean menuIsOpen() {
        return mMenu != null;

    }

    //关闭菜单
    public void closeMenu() {
        if (mMenu != null) {
            mMenu.closeMenu();//调用关闭菜单按钮
        }
        mMenu = null;//将菜单制空

    }

}

